package com.meiyuetao.myt.customer.web.action;

import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.meiyuetao.myt.core.constant.BizDataDictCategoryEnum;
import com.meiyuetao.myt.core.web.MytBaseController;
import com.meiyuetao.myt.customer.entity.*;
import com.meiyuetao.myt.customer.entity.CustomerAccountHist.CustomerAccountHistAccountTypeEnum;
import com.meiyuetao.myt.customer.entity.CustomerAccountHist.CustomerAccountHistOccurTypeEnum;
import com.meiyuetao.myt.customer.service.*;
import com.meiyuetao.myt.md.entity.CommodityViewStat;
import com.meiyuetao.myt.sale.entity.BoxOrder;
import com.meiyuetao.myt.sale.service.BoxOrderService;
import com.meiyuetao.o2o.entity.ObjectR2Pic;
import com.meiyuetao.o2o.entity.ObjectR2Pic.ObjectPicTypeEnum;
import lab.s2jh.core.annotation.MetaData;
import lab.s2jh.core.pagination.GroupPropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter.MatchType;
import lab.s2jh.core.security.AuthContextHolder;
import lab.s2jh.core.service.BaseService;
import lab.s2jh.core.util.DateUtils;
import lab.s2jh.core.web.annotation.SecurityControlIgnore;
import lab.s2jh.core.web.view.OperationResult;
import org.apache.commons.collections.CollectionUtils;
import org.apache.struts2.rest.HttpHeaders;
import org.h2.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.math.BigDecimal;
import java.util.*;

@MetaData("CustomerProfileController")
public class CustomerProfileController extends MytBaseController<CustomerProfile, Long> {

    @Autowired
    private CustomerProfileService customerProfileService;
    @Autowired
    private ReceiveAddressService receiveAddressService;
    @Autowired
    private BoxOrderService boxOrderService;
    @Autowired
    private CustomerAccountHistService customerAccountHistService;
    @Autowired
    private SsoUserService ssoUserService;
    @Autowired
    private CustomerCoinsHistoryService customerCoinsHistoryService;

    @Override
    protected BaseService<CustomerProfile, Long> getEntityService() {
        return customerProfileService;
    }

    @Override
    protected void checkEntityAclPermission(CustomerProfile entity) {
    }

    public HttpHeaders commodityViewStats() {
        List<CommodityViewStat> commodityViewStats = bindingEntity.getCommodityViewStats();
        setModel(commodityViewStats);
        return buildDefaultHttpHeaders();
    }

    @Override
    @MetaData("查看")
    @SecurityControlIgnore
    public HttpHeaders view() {
        GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        // 审核通过的
        groupPropertyFilter.forceAnd(new PropertyFilter(MatchType.EQ, "providerUid", bindingEntity.getCustomerName()));
        String typeNum = bindingEntity.getCustomerNameType();
        String typeStr = "";
        switch (Integer.valueOf(typeNum)) {
            case 1:
                typeStr = "SinaWeibo";
                break;
            case 0:
                typeStr = "IYouBoxUID";
                break;
            case 7:
                typeStr = "QQ";
                break;
            case 9:
                typeStr = "CHINABABY";
                break;
            case 10:
                typeStr = "MGMT";
                break;
            default:
                typeStr = "";
        }
        groupPropertyFilter.forceAnd(new PropertyFilter(MatchType.EQ, "providerType", typeStr));
        List<SsoUser> ssoUsers = ssoUserService.findByFilters(groupPropertyFilter);
        if (ssoUsers.size() == 1) {
            bindingEntity.setSsoUser(ssoUsers.get(0));
        }
        return buildDefaultHttpHeaders("viewBasic");
        // return buildDefaultHttpHeaders();
        // return super.view();
    }

    @Override
    @MetaData("读取缓存数据")
    protected void setupDetachedBindingEntity(Long id) {
        bindingEntity = getEntityService().findDetachedOne(id, "shopPagePics");
    }

    @Override
    @MetaData("保存")
    public HttpHeaders doSave() {
        String shop = getParameter("c2cShopInfo.shopName");
        if (StringUtils.isNullOrEmpty(shop)) {
            bindingEntity.setC2cShopInfo(null);
        }
        List<ObjectR2Pic> shopPagePics = bindingEntity.getShopPagePics();
        // 新追加的店铺图关联设定
        if (!CollectionUtils.isEmpty(shopPagePics)) {
            for (ObjectR2Pic shopPagePic : shopPagePics) {
                if (shopPagePic.getObjectType() != null) {
                    continue;
                }
                shopPagePic.setObjectSid(bindingEntity.getId());
                shopPagePic.setObjectType(ObjectPicTypeEnum.SHOP_PAGE_PIC);
            }
        }
        return super.doSave();
    }

    @Override
    @MetaData("删除")
    public HttpHeaders doDelete() {
        return super.doDelete();
    }

    @Override
    @MetaData("查询")
    public HttpHeaders findByPage() {
        return super.findByPage();
    }

    @Override
    @MetaData("预先编辑")
    public void prepareEdit() {
        if (entityClass == null) {
            return;
        }
        if (!StringUtils.isNullOrEmpty(this.getParameter("id"))) {
            Long sid = Long.valueOf(this.getParameter("id"));
            CustomerProfile entity = customerProfileService.findOne(sid);
            if (entity == null) {
                throw new IllegalArgumentException("Object for sid[" + sid + "] not exist");
            }
            GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
            groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "customerProfile", entity));
            List<ReceiveAddress> receiveAddressList = receiveAddressService.findByFilters(groupPropertyFilter);
            if (receiveAddressList.size() > 0) {
                this.getRequest().setAttribute("receiveAddressList", receiveAddressList);
            }
        }
        super.prepareEdit();
    }

    @MetaData("客户来源类型")
    public Map<String, String> getCustomerNameTypeMap() {
        return this.findMapDataByDataDictPrimaryKey(BizDataDictCategoryEnum.IYOUBOX_CUSTOMER_NAME_TYPE.name());
    }

    @MetaData("订单信息")
    public HttpHeaders boxOrders() {
        GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "customerProfile", bindingEntity));
        List<BoxOrder> boxOrders = boxOrderService.findByFilters(groupPropertyFilter);
        setModel(buildPageResultFromList(boxOrders));
        return buildDefaultHttpHeaders();
    }

    @MetaData("支付信息")
    public HttpHeaders customerAccountHists() {
        GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "customerProfile", bindingEntity));
        List<CustomerAccountHist> customerAccountHists = customerAccountHistService.findByFilters(groupPropertyFilter);
        setModel(buildPageResultFromList(customerAccountHists));
        return buildDefaultHttpHeaders();
    }

    @MetaData(value = "常用商品数据")
    @SecurityControlIgnore
    public HttpHeaders frequentUsedDatas() {
        Set<Map<String, Object>> datas = Sets.newHashSet();
        Collection<CustomerProfile> items = customerProfileService.findFrequentUsedCustomerProfiles();
        for (CustomerProfile item : items) {
            Map<String, Object> data = Maps.newHashMap();
            data.put("id", item.getId());
            data.put("display", item.getFriendlyName());
            datas.add(data);
        }
        setModel(datas);
        return buildDefaultHttpHeaders();
    }

    @MetaData(value = "补发签到")
    public HttpHeaders reissueSign() {
        CustomerAccountHist customerAccountHist = new CustomerAccountHist();
        customerAccountHist.setAmount(new BigDecimal(getParameter("reissueSignAmount")));
        customerAccountHist.setSysMemo(getParameter("reissueSignMemo") + "--" + AuthContextHolder.getAuthUserPin() + "补发签到" + ":" + DateUtils.formatTimeNow());
        customerAccountHist.setOccurTime(new Date());
        customerAccountHist.setOccurType(CustomerAccountHistOccurTypeEnum.CHECKIN);
        customerAccountHist.setAccountType(CustomerAccountHistAccountTypeEnum.CHECKIN);
        customerProfileService.reissueSign(bindingEntity, customerAccountHist);
        setModel(OperationResult.buildSuccessResult("补发签到成功……"));
        return buildDefaultHttpHeaders();
    }

    @Override
    @MetaData("非LAMAVC即美月淘")
    public void appendFilterProperty(GroupPropertyFilter groupPropertyFilter) {
        if (groupPropertyFilter.getFilters() != null) {
            List<PropertyFilter> filters = new ArrayList<PropertyFilter>();
            for (PropertyFilter pf : groupPropertyFilter.getFilters()) {
                if ("customerFrom".equals(pf.getPropertyNames()[0]) && "NONE".equals(pf.getMatchValue())) {
                    pf = new PropertyFilter(MatchType.NE, "customerFrom", "LAMAVC");
                }
                if ("isMeivd".equals(pf.getPropertyNames()[0]) && "true".equals(pf.getMatchValue().toString())) {
                    pf = new PropertyFilter(MatchType.NU, "meivdLastLogOnTime", true);
                }
                if ("isMeivd".equals(pf.getPropertyNames()[0]) && "false".equals(pf.getMatchValue().toString())) {
                    pf = new PropertyFilter(MatchType.NN, "meivdLastLogOnTime", true);
                }
                filters.add(pf);
            }
            groupPropertyFilter.setFilters(filters);
        }
    }

    @MetaData("微信账号解绑")
    public HttpHeaders releaseWeixin() {
        String weixinId = getParameter("weixinId");
        CustomerProfile customerProfile = customerProfileService.findByProperty("weixinId", weixinId);
        if (customerProfile != null) {
            customerProfile.setWeixinId("");
            weixinId = "微信解绑账号为：" + weixinId + "<br>";
            String adminMemo = customerProfile.getAdminMemo();
            customerProfile.setAdminMemo(adminMemo == null ? weixinId : adminMemo + weixinId);
            customerProfileService.save(customerProfile);
            setModel(OperationResult.buildSuccessResult("解绑成功"));
        } else {
            setModel(OperationResult.buildFailureResult("该微信账号不存在"));
        }
        return buildDefaultHttpHeaders();
    }

    // @MetaData("[导入到集市店铺信息表]")
    // public HttpHeaders importIntoC2cShopInfo() {
    // Collection<CustomerProfile> entities = this.getEntitiesByParameterIds();
    // for (CustomerProfile customerProfile : entities) {
    // C2cShopInfo c2cShopInfo = new C2cShopInfo();
    // c2cShopInfo.setCustomerProfile(customerProfile);
    // // 保证金 初始化为 0
    // c2cShopInfo.setCautionMoney(BigDecimal.ZERO);
    // // 补贴额
    // c2cShopInfo.setSubsidy(BigDecimal.ZERO);
    // // 补贴上限
    // c2cShopInfo.setSubsidyCap(BigDecimal.ZERO);
    // // 现行赔付额
    // c2cShopInfo.setAdvancePayouts(BigDecimal.ZERO);
    // c2cShopInfoService.save(c2cShopInfo);
    // }
    // setModel(OperationResult.buildSuccessResult("导入到集市店铺信息操作完成"));
    // return buildDefaultHttpHeaders();
    // }
    @MetaData("积分充值")
    public HttpHeaders recharge() {
        String rollbackErr = "";
        String coinVal = getParameter("coinValue");
        BigDecimal coinBig = BigDecimal.ZERO;
        if (org.apache.commons.lang3.StringUtils.isNotBlank(coinVal)) {
            coinBig = BigDecimal.valueOf(Integer.valueOf(coinVal));
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(getParameter("ids"))) {
            Long[] ids = this.getSelectSids();
            List<CustomerProfile> list = customerProfileService.findAll(ids);
            for (CustomerProfile cp : list) {
                BigDecimal oldCoin = BigDecimal.ZERO;
                BigDecimal oldFreezeCoin = BigDecimal.ZERO;
                BigDecimal oldBaseScore = BigDecimal.ZERO;
                BigDecimal oldFreezenScore = BigDecimal.ZERO;
                if (null != cp.getCoins()) {
                    oldCoin = cp.getCoins();
                }
                if (null != cp.getFreezeCoins()) {
                    oldFreezeCoin = cp.getFreezeCoins();
                }
                if (null != cp.getBaseNewScore()) {
                    oldBaseScore = cp.getBaseNewScore();
                }
                if (null != cp.getFreezenNewScore()) {
                    oldFreezenScore = cp.getFreezenNewScore();
                }
                CustomerCoinsHistory cch = new CustomerCoinsHistory();
                cch.setCoins(coinBig);
                cch.setBaseNewScore(oldBaseScore);
                cch.setCoinsBefore(oldCoin);
                cch.setCoinsAfter(oldCoin.add(coinBig));
                cch.setCustomerProfile(cp);
                if (coinBig.compareTo(BigDecimal.ZERO) > 0) {
                    cch.setOperationType(CustomerCoinsHistory.OperationTypeEnum.CHARGE);
                } else {
                    if (oldBaseScore.add(coinBig).compareTo(BigDecimal.ZERO) <= 0) {
                        rollbackErr = "反充值失败";
                        continue;
                    }
                    cch.setOperationType(CustomerCoinsHistory.OperationTypeEnum.RECHARGE);
                }
                cch.setMemo("手动充值" + coinBig + "积分");
                customerCoinsHistoryService.save(cch);
                cp.setCoins(oldCoin.add(coinBig));
                cp.setBaseNewScore(oldBaseScore.add(coinBig));
                // 充值积分的30%将被冻结  2016-04-12 冻结积分暂时取消
                // cp.setFreezeCoins(oldFreezeCoin.add(coinBig.multiply(BigDecimal.valueOf(0.3))));
                // cp.setFreezenNewScore(oldFreezenScore.add(coinBig.multiply(BigDecimal.valueOf(0.3))));
                cp.setFreezeCoins(BigDecimal.ZERO);
                cp.setFreezenNewScore(BigDecimal.ZERO);
                cp.setCustomerFrom("SD");
                cp.setLastRechargeTime(new Date());
                customerProfileService.save(cp);
            }
        }
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(rollbackErr)) {
            setModel(OperationResult.buildFailureResult(rollbackErr));
        } else {
            setModel(OperationResult.buildSuccessResult("充值成功"));
        }
        return buildDefaultHttpHeaders();
    }

    private File customerExcel;

    @MetaData("积分充值")
    public HttpHeaders importCoins(){
        if (customerExcel == null) {
            setModel(OperationResult.buildFailureResult("请选择上传文件"));
            return buildDefaultHttpHeaders();
        }
        String failErpIds = "";
        try {
            failErpIds = customerProfileService.importCoins(customerExcel);
        } catch (Exception e) {
            setModel(OperationResult.buildFailureResult("excel解析错误"));
            return buildDefaultHttpHeaders();
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(failErpIds)) {
            setModel(OperationResult.buildFailureResult(failErpIds));
        } else {
            setModel(OperationResult.buildSuccessResult("成功同步"));
        }
        return buildDefaultHttpHeaders();
    }

    public File getCustomerExcel() {
        return customerExcel;
    }

    public void setCustomerExcel(File customerExcel) {
        this.customerExcel = customerExcel;
    }
}